package nway_fs_ctl

import (
	_ "encoding/json"
	"strings"

	"nway_dsr/nway_dsr/nway_fs_db"
	"nway_dsr/nway_dsr/utils/eventsocket"
	"nway_dsr/nway_dsr/utils/log"
	"os/exec"
)

func proc_hangup(c *eventsocket.Connection, e *eventsocket.Event) {

}

func proc_hangup_complete(c *eventsocket.Connection, e *eventsocket.Event) {

	var uuid, other_uuid string

	uuid = e.Get("Caller-Unique-Id")

	if len(uuid) < 1 {
		uuid = e.Get("Caller-Unique-ID")
	}
	other_uuid = e.Get("Other-Leg-Unique-Id")
	if len(other_uuid) < 1 {
		other_uuid = e.Get("Other-Leg-Unique-ID")
	}
	logger.Debug("uuid:%s,other_uuid:%s\n", uuid, other_uuid)
	go nway_dsr_db.QueryAndInsertCdr(uuid, other_uuid)

}

/*

Event-Subclass: dsr%3A%3Arecording
Event-Name: CUSTOM
Core-UUID: fbfc3df4-e24e-11e8-8c7c-65bc471c260e
FreeSWITCH-Hostname: lihao.nway
FreeSWITCH-Switchname: lihao.nway
FreeSWITCH-IPv4: 10.0.0.21
FreeSWITCH-IPv6: %3A%3A1
Event-Date-Local: 2018-11-09%2010%3A33%3A01
Event-Date-GMT: Fri,%2009%20Nov%202018%2002%3A33%3A01%20GMT
Event-Date-Timestamp: 1541730781207181
Event-Calling-File: mod_dsr.c
Event-Calling-Function: nway_dsr_callback
Event-Calling-Line-Number: 449
Event-Sequence: 51917
dsr_record_file: /usr/local/freeswitch/recordings/R_be030c06-e3c7-11e8-be34-65bc471c260e.wav
call_id: b835b300-e3c7-11e8-b1d4-65bc471c260e
Channel: b835b300-e3c7-11e8-b1d4-65bc471c260e
nway_flag: read

*/

func Nway_exec(strcmd string, arg ...string) (error, string) {
	cmd := exec.Command(strcmd, arg...)
	buf, err := cmd.Output()
	logger.Debug("%s\n%s\r\n", buf, err)
	return err, string(buf)

	//cmd := exec.Command("ls", "-l")
}
func proc_custom(c *eventsocket.Connection, e *eventsocket.Event) {
	//e.PrettyPrint()
	//logger.Info(e.String())
	//fsruntime := NewFsRuntime()
	evt_subclass := e.Get("Event-Subclass")
	logger.Debug("event subclass:", evt_subclass)
	if strings.Trim(evt_subclass, " ") == "dsr::recording" {
		//e.PrettyPrint()
		//

		call_id := e.Get("Variable_call_id")
		if len(call_id) < 2 {
			call_id = e.Get("Call_Id")
		}
		dsr_record_file := e.Get("Variable_dsr_record_file")
		if len(dsr_record_file) < 2 {
			dsr_record_file = e.Get("Dsr_Record_File")
		}
		//to add asr result
		logger.Debug("To recognize:", dsr_record_file, "   use app:", ASR)
		var content string = ""

		err, result := Nway_exec(ASR, APPID, dsr_record_file)
		if err == nil {
			content = result
		}
		logger.Debug("recognation:", result)
		nway_flag := e.Get("Variable_nway_flag")
		if len(nway_flag) < 2 {
			nway_flag = e.Get("Nway_Flag")
		}

		err, must_hangup := nway_dsr_db.InsertDSRRecord(call_id, nway_flag, dsr_record_file, content)
		if err != nil {
			//logger.Error(err)
		}
		if must_hangup {
			//挂机
			Nway_uuid_hangup(call_id)
		}
	}

}

func proc_execute_complete(c *eventsocket.Connection, e *eventsocket.Event) {

}
